#include "parser.h"

static void download_callback(char *buf, int size, void *arg)
{
	struct download_task *task = arg;
	if(task->position + size > task->size)
	{
		void *ret;
		task->size *= 2;
		ret = realloc(task->buffer, task->size);
		if(ret <= 0)
		{
			task->error = ERROR_NO_MEMORY;
			cancel_http_download(task->http);
			return;
		}
	}
	memcpy(task->buffer+task->position, buf ,size);
	task->position += size;
}

int init_download_task(struct download_task *task, char *url)
{
	task->size = NORMAL_BUFFER_SIZE;
	task->buffer = malloc(NORMAL_BUFFER_SIZE);
	task->position = 0;
	task->url = url;
	if(!task->buffer)
		return -1;
	task->http = create_http_task(url, download_callback, task);
	if(!task->http)
	{
		free(task->buffer);
		task->buffer = NULL;
		task->size = 0;
		return ERROR_NO_MEMORY;
	}
	task->error = 0;
	return 1;
}

int download(struct download_task *task)
{
	int ret = -1;
	int retry = RETRY_TIME;
	while(retry--)
	{
		ret = start_http_download(task->http);
		if(ret >= 0)
			break;
		usleep(200000);
	}
	free_http_task(task->http);
	task->http = NULL;

	if(task->error)
		return task->error;
	if(ret < 0)
		ret = ERROR_DOWNLOAD_HTTP;
	else
		ret = 0;
	return ret;
}

void cancel_download(struct download_task *task)
{
	cancel_http_download(task->http);
}

void free_download_task(struct download_task *task)
{
	free(task->buffer);
	task->buffer = NULL;
	task->size = 0;
}
